package bot.controller;

import bot.mapper.FriendMapper;
import bot.pojo.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/baidu")
public class BaiduTranslate {//调用百度翻译接口

    private String APPID = "20230121001536736";
    private String APPKEY = "xs9YtYlvL1uEDjKg90v1";
    Integer salt = 1435660288;
    @GetMapping("/translate")
    public String Translate(String g) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        g = g.trim();
        String md5 = APPID + g + salt + APPKEY;
        String crypt = crypt(md5);
        System.out.println(crypt);
        String s = HttpHelp.sendGet(
                "api.fanyi.baidu.com/api/trans/vip/translate?q="+g+"&from=auto&to=zh&appid="+APPID+"&salt="+salt+"&sign="+crypt.toLowerCase()
        );
        //s = URLDecoder.decode(s,"utf-8");
        BaiDuReturn t = JSONObject.parseObject(s,BaiDuReturn.class);
        return t.getTrans_result().getDst();
    }

    public static String crypt(String str) {
        if (str == null || str.length() == 0) {
            throw new IllegalArgumentException("String to encript cannot be null or zero length");
        }
        StringBuffer hexString = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] hash = md.digest();
            for (int i = 0; i < hash.length; i++) {
                if ((0xff & hash[i]) < 0x10) {
                    hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
                } else {
                    hexString.append(Integer.toHexString(0xFF & hash[i]));
                }
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return hexString.toString();
    }
    private FriendExample friendExample = new FriendExample();
    @Autowired
    private FriendMapper friendMapper ;
    //百度授权回调地址
    @GetMapping("/returnData")//返回的code和绑定的qq号
    public Object returnData(String code , String state){
        //通过code获取token
        String s = HttpHelp.sendGet("openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code=" + code + "&client_id=5YWXrO9cahksXbKY3HVvG3QIfImpC1j0&client_secret=01309InebXRzHIoGOobpcEcTl5hgQ5U0&redirect_uri=http://8.130.83.222:9000/baidu/returnData");
        //把json串转为对象
        BaiduData baiduData = JSONObject.parseObject(s, BaiduData.class);
        System.out.println(baiduData);
        //查询这个QQ号有没有绑定过，绑定过的只更新
        friendExample.clear();
        friendExample.createCriteria().andFriendQqidEqualTo(state);
        List<Friend> friends = friendMapper.selectByExample(friendExample);
        if (friends.size() > 0){
            friends.get(0).setAccessToken(baiduData.getAccessToken());
            friendMapper.updateByPrimaryKey(friends.get(0));
            return "ok";
        }
        //不存在新增
        Friend friend = new Friend();
        //绑定的qq号
        friend.setFriendQqid(state);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HHLmm");
        friend.setCreateTime(simpleDateFormat.format(new Date()));
        friend.setAccessToken(baiduData.getAccessToken());
        friendMapper.insert(friend);
        return "ok";
    }
    @GetMapping("/tre")
    public Object tre(){
        return "true";
    }
    //绑定状态查询
    @GetMapping("/select")
    public Object select(String qqid){
        friendExample.clear();
        friendExample.createCriteria().andFriendQqidEqualTo(qqid);
        long l = friendMapper.countByExample(friendExample);
        if(l > 0){
            return "true";
        }
        else {
            return "false";
        }
    }
    //查询文件
    @GetMapping("/selectFile")
    public Object selectFile(String qqid , String name){
        friendExample.clear();
        friendExample.createCriteria().andFriendQqidEqualTo(qqid);
        List<Friend> friends = friendMapper.selectByExample(friendExample);
        if (friends.size() == 0){
            //没绑定直接返回null
            return null;
        }
        String token = friends.get(0).getAccessToken();
        String url = "pan.baidu.com/rest/2.0/xpan/file?method=search&access_token="+token+"&key="+name;
        String s = HttpHelp.sendGet(url);
        return s;
    }
    //@ApiOperation("创建文件分享链接")
    @GetMapping("/ShareLinkFile")
    public Object ShareLink(String qqid ,String fileid) throws IOException {
        System.out.println(qqid);
        friendExample.clear();
        friendExample.createCriteria().andFriendQqidEqualTo(qqid);
        List<Friend> friends = friendMapper.selectByExample(friendExample);
        if (friends.size() == 0){
            //没绑定直接返回null
            return null;
        }
        Map map = new HashMap();
//        map.put("appid","31430604");
//        map.put("access_token",friends.get(0).getAccessToken());
//        map.put("product","product");
        //文件名需要拼接成json数组
        fileid = "["+fileid+"]";
        map.put("fsid_list",fileid);
        map.put("period",7);
        //分享密码默认123456
        map.put("pwd","1234");
        String s = JSONObject.toJSONString(map);
       // s = JSONObject.toJSONString(s);
       // String s1 = HttpHelp.sendPost("https://pan.baidu.com/apaas/1.0/share/set?product=netdisk&appid=31430604&access_token="+friends.get(0).getAccessToken(), s);

        String url = "https://pan.baidu.com/apaas/1.0/share/set?product=netdisk&appid=31430604&access_token="+friends.get(0).getAccessToken();
        String requestBody = s;

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法为POST
        con.setRequestMethod("POST");

        // 设置请求头
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        // 启用输出，表示我们将向服务器写入数据
        con.setDoOutput(true);

        // 将请求正文作为字节数组编码为UTF-8
        byte[] requestBodyBytes = requestBody.getBytes(StandardCharsets.UTF_8);

        // 获取输出流并在其中写入请求体
        OutputStream outputStream = con.getOutputStream();
        outputStream.write(requestBodyBytes);
        outputStream.flush();
        outputStream.close();

        // 获取HTTP响应码
        int responseCode = con.getResponseCode();
        System.out.println("Response Code : " + responseCode);

        return con;
    }
    @GetMapping("/text")
    public Object text(){
        return "ok";
    }
}
